package com.woodws.core.resolver;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class ListArgumentResolver implements HandlerMethodArgumentResolver {

    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() != List.class;
    }

    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        List list = new ArrayList();
        String[] names = webRequest.getParameterValues("name");
        String[] ages = webRequest.getParameterValues("age");

        for (int i = 0; i < names.length; i++) {
            Object object = parameter.getConstructor().newInstance();
            BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);

            String name = names[i];
            String age = ages[i];
            beanWrapper.setPropertyValue("name", name);
            beanWrapper.setPropertyValue("age", age);

            list.add(object);
        }
        return list;
    }

}
